package com.huobao.yunying.activitys;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.zhifubao_apliy.ParamsUtil;
import com.huobao.yunying.zhifubao_apliy.PayResult;
import com.huobao.zhangying.R;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.xutils.view.annotation.ViewInject;

import java.util.Map;

public class Act_Shouyintai extends HuobaoBaseActivity implements OnClickListener {

	// 订单号
	@ViewInject(R.id.tv_dingdanhao)
	private TextView tv_dingdanhao;
	// 价格
	@ViewInject(R.id.tv_price)
	private TextView tv_price;
	// 支付宝
	@ViewInject(R.id.tv_pay_zhifubao)
	private TextView tv_pay_zhifubao;
	// 微信
	@ViewInject(R.id.tv_pay_weixin)
	private TextView tv_pay_weixin;

	// intent.putExtra("order_amount", order_amount);
	// intent.putExtra("order_sn", order_sn);
	private String order_amount, order_sn,content;

	@Override
	protected int getContentView() {
		return R.layout.layout_shouyintai;
	}

	@Override
	protected String getTitleText() {
		return "收银台";
	}
	/**
	 * intent.putExtra("order_sn", order_sn);
		intent.putExtra("price", price);
		intent.putExtra("content", content);
	 */

	@Override
	protected void init() {
		order_amount = getIntent().getStringExtra("price");
		order_sn = getIntent().getStringExtra("order_sn");
		content = getIntent().getStringExtra("content");
		tv_dingdanhao.setText("订单号：" + order_sn);
		tv_price.setText("￥" + order_amount);
		tv_pay_zhifubao.setOnClickListener(this);
		tv_pay_weixin.setOnClickListener(this);
		EventBus.getDefault().post("", "refreshGouwche");
	}
	/**
	 * bank_type 3,微信APP，4支付宝APP
	 * @param type
	 */
	private void pay(final int type){
		Map<String, String> map = HttpUtil.getParams("app","cashier","act","ajaxepaylog","bank_type",type+"","order_amount",order_amount,"order_sn",order_sn);
		Http.getInstant().sendRequest(context, map, new HttpListener() {
			
			@Override
			public void onHttpSuccess(String result) {
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
				try {
					String str = jsonObject.getString("retval");
					if(TextUtils.isEmpty(str)){
						Toast.makeText(context, "生成订单失败！", Toast.LENGTH_SHORT).show();
					}else{
						if(str.equals("faile")){
							Toast.makeText(context, "生成订单失败！", Toast.LENGTH_SHORT).show();
						}else if(str.equals("success")){
							switch(type){
							case 3:
								payWeixin();
								break;
							case 4:
								payZhifubao();
								break;
							}
						}
					}
				} catch (Exception e) {
					Toast.makeText(context, "生成订单失败！", Toast.LENGTH_SHORT).show();
				}
				
			}
			
			@Override
			public void onHttpError(String error) {

			}
		});
	}

	protected void payZhifubao() {
		content = "zhangyingtianxia";
		String orderInfo = ParamsUtil.getInstant().getParams("zhangying", content, order_amount, order_sn);
		pay(orderInfo);
	}

	protected void payWeixin() {
		final IWXAPI api = WXAPIFactory.createWXAPI(this, "wx9542aca81974f823");

		float price = Float.parseFloat(order_amount);
		price = price * 100;
		price = Math.round(price);

		int nPrice = (int)price;
		String url = "http://app.zhangyingtianxia.com/app/wxpay/WechatPayBase.php?body=微信APP支付&price="+nPrice+"&order_sn="+order_sn;
		tv_pay_weixin.setEnabled(false);
		Toast.makeText(this, "获取订单中...", Toast.LENGTH_SHORT).show();
		Http.getInstant().sendRequest(context, true, url, null, new HttpListener() {
			
			@Override
			public void onHttpSuccess(String result) {
				try {
					JSONObject json = new JSONObject(result);
					PayReq req = new PayReq();
					req.appId = json.getString("appid");
					req.partnerId = json.getString("partnerid");
					req.prepayId = json.getString("prepayid");
					req.nonceStr = json.getString("noncestr");
					req.timeStamp = json.getString("timestamp");
					req.packageValue = json.getString("package");
					req.sign = json.getString("sign");
					req.extData = "app data"; // optional
					Toast.makeText(Act_Shouyintai.this, "正常调起支付", Toast.LENGTH_SHORT).show();
					// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
					api.sendReq(req);
				} catch (Exception e) {
					Log.e("PAY_GET", "异常：" + e.getMessage());
					Toast.makeText(Act_Shouyintai.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}
				tv_pay_weixin.setEnabled(true);
			}
			
			@Override
			public void onHttpError(String error) {

			}
		});
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_pay_zhifubao:
			pay(4);
			break;
		case R.id.tv_pay_weixin:
			pay(3);
			break;
		}
	}

	private void pay(final String orderInfo) {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				new Thread() {
					public void run() {
						// 构造PayTask 对象
						PayTask alipay = new PayTask(Act_Shouyintai.this);
						// 调用支付接口，获取支付结果
						String result = alipay.pay(orderInfo, true);

						Message msg = new Message();
						msg.what = 1;
						msg.obj = result;
						mHandler.sendMessage(msg);
					};
				}.start();
			}
		}, 1000);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(Act_Shouyintai.this, "支付成功", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(context, Act_DingDanGuanli.class);
					startActivity(intent);
					finish();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失败
					// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(Act_Shouyintai.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(Act_Shouyintai.this, "支付失败", Toast.LENGTH_SHORT).show();

					}
				}
				break;
			default:
				break;
			}
		};
	};
	@Override
	protected void onStop() {
		super.onStop();
	}

}
